package com.zhy.sunmi;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.zhy.greendao.gen.DaoMaster;
import com.zhy.greendao.gen.DaoSession;

import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import POSAPI.POSInterfaceAPI;
import POSAPI.POSUSBAPI;
import POSSDK.POSSDK;
import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

/**
 * @author zhouhongyang
 */
public class MyApplication extends Application {
    public static long MachineId = 0;
    public static String UserName = "";
    public static String postion = "";
    public static String api_token = "";
    public static long UserId;
    private static MyApplication mInstance;
    private static DaoSession daoSession;
    IWoyouService iWoyouService;

    public static final int POS_SUCCESS = 1000;
    private int error_code = 0;
    public static TestPrintInfo testprint;
    public static POSInterfaceAPI interface_usb = null;
    public static POSSDK pos_usb = null;
    private SharedPreferences sf;
    private static String TAG = "Socket";
    private Handler handler;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        initDreenDao();
        initCashDrawer();
        initPrint();
        sf = getSharedPreferences("config", Activity.MODE_PRIVATE);
        initCardPay();
        MachineId=MyApplication.getInstance().getMachineId();

    }


    public void saveUrl(String url) {
        sf.edit().putString("url", url).apply();
    }

    public String getUrl() {
        String url = sf.getString("url", "");
        return url;
    }

    public void saveMachineId(long url) {
        sf.edit().putLong("MachineId", url).apply();
    }

    public Long getMachineId() {
        Long url = sf.getLong("MachineId",-1);
        return url;
    }


    public void saveTid(String tid) {
        sf.edit().putString("tid", tid).apply();
    }

    public String getTid() {
        String tid = sf.getString("tid", "");
        return tid;
    }


    private void initPrint() {


        interface_usb = new POSUSBAPI(this);
        error_code = interface_usb.OpenDevice();
        if (error_code != POS_SUCCESS) {
            String a = "Cannot connect to printer. Please check your printer!";
            Toast.makeText(getApplicationContext(), a, Toast.LENGTH_LONG).show();
        } else {
            pos_usb = new POSSDK(interface_usb);
//            Toast.makeText(getApplicationContext(), "Open Port OK!.", Toast.LENGTH_LONG).show();

        }
        testprint = new TestPrintInfo();
    }

    private void initCashDrawer() {
        Intent intent = new Intent();
        intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
        intent.setPackage("woyou.aidlservice.jiuiv5");
        getApplicationContext().bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    /**
     * greendao数据库初始化
     */
    private void initDreenDao() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "YoYo.db");
        Database db = devOpenHelper.getWritableDb();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession(IdentityScopeType.None);
    }


    /***
     *
     * 单例模式中获取唯一的ExitApplication 实例
     */
    public static MyApplication getInstance() {
        if (null == mInstance) {
            mInstance = new MyApplication();
        }
        return mInstance;

    }


    /**
     * 获取 DaoSession
     *
     * @return
     */
    public static DaoSession getDaoSession() {
        return daoSession;
    }


    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            iWoyouService = IWoyouService.Stub.asInterface(binder);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(getApplicationContext(), "链接失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBindingDied(ComponentName name) {
            Toast.makeText(getApplicationContext(), "链接失败", Toast.LENGTH_SHORT).show();
        }
    };


    public void openCashDrawer() {
//        try {
//            int a = iWoyouService.getOpenDrawerTimes();
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }

        if (iWoyouService == null) {
            return;
        }

        try {
            iWoyouService.openDrawer(new ICallback.Stub() {
                @Override
                public void onRunResult(boolean isSuccess, int code, String msg) throws RemoteException {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public IBinder asBinder() {
                    return null;
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private WebSocketClient webSocketClient;

    public WebSocketClient getWebSocketClient() {
        return webSocketClient;
    }

    public void setWebSocketClient(WebSocketClient webSocketClient) {
        this.webSocketClient = webSocketClient;
    }

    public void initCardPay() {
         String url = MyApplication.getInstance().getUrl();
        URI serverURI = URI.create(url);
        webSocketClient = new WebSocketClient(serverURI) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                Log.d(TAG, "onOpen");
            }

            @Override
            public void onMessage(String message) {
                Message handlerMessage = Message.obtain();
                handlerMessage.obj = message;
                if(handler!=null){
                    handler.sendMessage(handlerMessage);
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                Log.d(TAG, "onClose");
            }

            @Override
            public void onError(Exception ex) {
                Log.d(TAG, "onError");
                webSocketClient.close();
//                webSocketClient.connect();
            }


        };
        webSocketClient.connect();

    }

    public void setHandler(Handler handler) {
        this.handler=handler;
    }


}
